package com.mrjy.integral.bo;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.mrjy.common.entity.IntegralExchange;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.integral.dao.IIntegralExchangeDao;
import com.mrjy.integral.dao.IIntegralExchangedLogDao;
import com.mrjy.integral.dto.IntegralExchangeDTO;

@Service
public class IntegralExchangeBo implements IIntegralExchangeBo {
	
	@Resource
	private IIntegralExchangeDao integralExchangeDao;
	@Resource
	private IIntegralExchangedLogDao integralExchangedLogDao;
	

	@Override
	public Object txInsert(IntegralExchangeDTO dto, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		//数据校验
		if (StringUtils.isBlank(dto.getIeName())) {
			map.put("err_code", 401);
			map.put("err_msg", "兑换物名称不能为空");
			return map;
		}
		if (StringUtils.isBlank(dto.getIeCoverUrl())) {
			map.put("err_code", 402);
			map.put("err_msg", "封面不能为空");
			return map;
		}
		if (dto.getTypeId()==null) {
			map.put("err_code", 403);
			map.put("err_msg", "类型不能为空");
			return map;
		}
		if (dto.getScore() ==null) {
			map.put("err_code", 404);
			map.put("err_msg", "积分不能为空");
			return map;
		}
		if (dto.getScore().intValue() < 0) {
			map.put("err_code", 405);
			map.put("err_msg", "积分必须是大于等于0的整数");
			return map;
		}
		
		try {
			if (StringUtils.isNotBlank(dto.getValidDateString())) {
				dto.setValidDate(new Timestamp(DateUtil.stringToLong(dto.getValidDateString(), DateUtil.FULL_DATE)));
			}
			if (dto.getCount()!=null) {
				dto.setCountBalance(dto.getCount());
			}
			dto.setCreateTime(new Timestamp(System.currentTimeMillis()));
			dto.setDisableFlag(0);
			dto.setIsExpire(0);//默认未到期
			if (dto.getTypeId() == 1) {
				try {
					dto.setVoucherMoney(Integer.parseInt(dto.getIeName().substring(0, dto.getIeName().indexOf("元"))));
				} catch (Exception e) {
					e.printStackTrace();
					map.put("err_code", 406);
					map.put("err_msg", "代金券名称格式有误");
					return map;
				}
			}
			integralExchangeDao.insert(dto);
			map.put("err_code", 200);
			map.put("err_msg", "添加成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "添加失败");
		}
		return map;
	}
	
	@Override
	public Object txUpdate(IntegralExchangeDTO dto, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		//数据校验
		if (StringUtils.isBlank(dto.getIeName())) {
			map.put("err_code", 401);
			map.put("err_msg", "兑换物名称不能为空");
			return map;
		}
		if (StringUtils.isBlank(dto.getIeCoverUrl())) {
			map.put("err_code", 402);
			map.put("err_msg", "封面不能为空");
			return map;
		}
		if (dto.getTypeId()==null) {
			map.put("err_code", 403);
			map.put("err_msg", "类型不能为空");
			return map;
		}
		if (dto.getScore() ==null) {
			map.put("err_code", 404);
			map.put("err_msg", "积分不能为空");
			return map;
		}
		if (dto.getScore().intValue() < 0) {
			map.put("err_code", 405);
			map.put("err_msg", "积分必须是大于等于0的整数");
			return map;
		}
		//如果更改类型为实物,则有效天数置为空
		if (dto.getTypeId()==0) {
			dto.setValidDateNum(null);
		}
		//修改有效数量,则剩余可兑换数量要一并更新(但必须>0)
		if (dto.getCount() != null) {
			IntegralExchange ie = integralExchangeDao.queryById(dto.getId());
			if (dto.getCount()-ie.getExchangedNum() <= 0) {
				map.put("err_code", 407);
				map.put("err_msg", "有效数量填写有误,请联系系统管理员");
				return map;
			}
			dto.setCountBalance(dto.getCount()-ie.getExchangedNum());
		}
		if (dto.getTypeId() == 1) {
			try {
				dto.setVoucherMoney(Integer.parseInt(dto.getIeName().substring(0, dto.getIeName().indexOf("元"))));
			} catch (Exception e) {
				e.printStackTrace();
				map.put("err_code", 406);
				map.put("err_msg", "代金券名称格式有误");
				return map;
			}
		}
		try {
			if (StringUtils.isNotBlank(dto.getValidDateString())) {
				
				long validDateLong = DateUtil.stringToLong(dto.getValidDateString(), DateUtil.FULL_DATE);
				dto.setValidDate(new Timestamp(validDateLong));
				
				if(validDateLong >= System.currentTimeMillis()){
					dto.setIsExpire(0);
				}else{
					dto.setIsExpire(1);
				}
			}
			int row = integralExchangeDao.updateById(dto);
			map.put("err_code", 200);
			map.put("err_msg", "成功更新"+row+"条记录");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "更新失败");
		}
		return map;
	}
	
	@Override
	public Object txUpdateDisableFlag(IntegralExchange exchange,
			HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		if (exchange.getIds()==null||exchange.getIds().length==0) {
			map.put("err_code", 400);
			map.put("err_msg", "请勾选要操作的记录");
			return map;
		}
		try {
			//如果该兑换物已被兑换且未失效,则不允许禁用
			for (Integer id : exchange.getIds()) {
				int count = integralExchangedLogDao.canBeDisabled(id);
				if (count > 0 && exchange.getDisableFlag() == 1) {
					map.put("err_code", 401);
					map.put("err_msg", "无法禁用,请联系系统管理员");
					return map;
				}
				
			}
			int row = integralExchangeDao.updateDisableFlag(exchange);
			map.put("err_code", 200);
			map.put("err_msg", "成功操作"+row+"条记录");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "操作失败");
		}
		return map;
	}
	
	@Override
	public Object queryPage(IntegralExchange exchange, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser){
		}
		try {
			int count = integralExchangeDao.queryCount(exchange);
			List<IntegralExchangeDTO> list = null;
			if (count>0) {
				list = integralExchangeDao.queryPage(exchange);
			}
			map.put("err_code", 200);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
			map.put("total", count);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "查询失败");
		}
		return map;
	}

	@Override
	public Object queryPageForBack(IntegralExchangeDTO dto,
			HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		try {
			int count = integralExchangeDao.queryCountForBack(dto);
			List<IntegralExchangeDTO> list = null;
			if (count>0) {
				list = integralExchangeDao.queryPageForBack(dto);
			}
			map.put("err_code", 200);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
			map.put("total", count);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "查询失败");
		}
		return map;
	}

	@Override
	public Object export(IntegralExchangeDTO dto, HttpSession session,HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		List<IntegralExchangeDTO> dataset = integralExchangeDao.queryPageForBack(dto);
		if (dataset == null || dataset.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		try {
			ExcelUtil.writeExcel(response, "积分兑换"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, IntegralExchangeDTO.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

	@Override
	public Object queryDetailById(IntegralExchange exchange, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser){
		}
		IntegralExchangeDTO dto = integralExchangeDao.queryDetailById(exchange);
		map.put("err_code", 200);
		map.put("err_msg", "查询成功");
		map.put("rows", dto);
		return map;
	}

	

	

}
